import "./index.css";

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";

import { DatePicker, message } from "antd";
import axios from "axios";
import InterIP from "../../IP/IP";

import OtherComponent from "../othercomponents";

let IP = InterIP().props.children;

// 时间日期组件
const { RangePicker } = DatePicker;

function onChange(value, dateString) {
  console.log("Selected Time: ", value);
  console.log("Formatted Selected Time: ", dateString);
}

function onOk(value) {
  console.log("onOk: ", value);
}

export default function ConfirmOrder() {
  var userID = document.cookie.slice(5);

  const navigate = useNavigate();

  const [store, setStore] = useState([]);

  const [address, setAddress] = useState([]);
  useEffect(() => {
    var userID = document.cookie.slice(5);
    axios.post("http://" + IP + ":3000/user/selAddress", {
      user_id: userID,
    }).then((res) => {
      setAddress((address) => (address = res.data));
    });
    axios.post('http://' + IP + ':3000/index/selStore', {

    }).then((res) => {
      let shopArr = res.data;
      axios.post("http://" + IP + ":3000/index/selEnsure", {
        user_id: userID,
      }).then((res) => {
        let arr = []
        res.data.forEach((v, k) => {
          arr[k] = {
            ensure_id: v.ensure_id,
            store_id: '',
            store_name: v.store_name,
            boss_name: '',
            boss_phone: '',
            total_price: 0,
            product: [],
          }
        });
        for (let i = 0; i < arr.length; i++) {
          for (let j = i + 1; j < arr.length; j++) {
            if (arr[i].store_name === arr[j].store_name) {
              arr.splice(j, 1);
              j--;
            }
          }
        }
        arr.forEach((v) => {
          res.data.forEach((val) => {
            if (v.store_name === val.store_name) {
              let value = JSON.parse(val.product);
              let smallArr = {
                product_name: value.product_name,
                product_number: value.product_number,
                product_specification: value.product_specification,
                product_price: value.product_price,
                product_img: value.product_img,
                buy_number: value.buy_number,
                product_id: value.product_id
              }
              v.product.push(smallArr)
              v.total_price += parseFloat(value.product_price) * value.buy_number
            }
          })
        })

        shopArr.forEach((value) => {
          arr.forEach((v) => {
            if (v.store_name === value.store_name) {
              v.store_id = value.store_id;
              v.boss_name = value.boss_name;
              v.boss_phone = value.boss_phone;
            }
          })
        })
        setStore((store) => (store = arr));
      });
    })

  }, []); // eslint-disable-line react-hooks/exhaustive-deps
  //修改默认地址
  function setDefaultAddresss(id, k) {
    return () => {
      axios
        .post("http://" + IP + ":3000/user/resetAddress", {
          default_address: "0",
          user_id: userID,
        })
        .then((res) => {
          axios
            .post("http://" + IP + ":3000/user/defaultAddress", {
              default_address: "1",
              address_id: id,
            })
            .then((res) => {
              axios
                .post("http://" + IP + ":3000/user/selAddress", {
                  user_id: userID,
                })
                .then((res) => {
                  setAddress((address) => (address = res.data));
                });
            });
        });
    };
  }

  // 删除地址
  function deleteAddress(k, id) {
    return () => {
      axios
        .post("http://" + IP + ":3000/user/delAddress", {
          address_id: id,
        })
        .then((res) => {
          console.log(res);
          setAddress(
            (address) =>
            (address = address.filter((v, key) => {
              return !(key === k);
            }))
          );
        });
    };
  }

  // 修改地址
  function bjsite(data) {
    return () => {
      navigate("/home/confirmorder/changeaddress", {
        state: {
          data: data,
        },
      });
    };
  }

  // 添加新地址
  function addAddress() {
    navigate("/home/confirmorder/addaddress");
  }
  // 返回购物车
  function backShoppingCart() {
    navigate("/home/shoppingCart");
  }
  // 求最终价格
  var sumMoneyAll = 0;
  for (let i = 0; i < store.length; i++) {
    sumMoneyAll += store[i].total_price + 5;
  }

  var onOff = true;
  function submitOrder() {
    let date = new Date(+new Date() + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
    var oAddress = document.getElementsByClassName("addressclass");
    var addressId = '';
    for (let i = 0; i < oAddress.length; i++) {
      if (oAddress[i].checked) {
        addressId = oAddress[i].value;
      }
    }
    if (onOff && addressId) {
      onOff = false;
      axios.post("http://" + IP + ":3000/index/getaddress", {
        address_id: parseInt(addressId),
      }).then((res) => {
        let address_id = res.data[0].address_id;
        let address_name = res.data[0].consignee;
        let address = res.data[0].area + " " + res.data[0].street
        let address_phone = res.data[0].contact_phone;

        axios.post('http://' + IP + ':3000/user/addIndent', {
          order_time: date,
          store_name: store[0].store_name,
          order_status: '待付款',
          total_price: sumMoneyAll,
          freight: '5.00',
          user_id: userID,
          product_id: store[0].product[0].product_id,
          order_evaluate: '0',
          product: '{"product_name":"' + store[0].product[0].product_name + '","product_number":' + store[0].product[0].product_number + ',"product_specification":"' + store[0].product[0].product_specification + '","product_price":' + store[0].product[0].product_price + ',"product_img":"' + store[0].product[0].product_img + '","buy_number":' + store[0].product[0].buy_number + ',"product_id":' + store[0].product[0].product_id + '}',
          address_id,
          address_name,
          address,
          address_phone,
          boss_name: store[0].boss_name,
          boss_phone: store[0].boss_phone,
        }).then((res) => {
          if (res.data.msg === '已添加到订单') {
            axios.post('http://' + IP + ':3000/index/delEnsure', {
              ensure_id: store[0].ensure_id,
            }).then((res) => {
              if (res.data.msg === '删除了') {
                navigate("/home/submitsuccess/apay", { state: { sumMoneyAll, date, address_id, shops: 1 } });
              }
            });
          }
        })
      })


    } else {
      if (addressId) {
        message.warning('别他妈点了!!!');
        message.warning('你想多付点钱，我也不介意!!!');
      } else {
        message.warning('你想送哪,送给我吗???')
      }
    }
  }

  return (
    <div className="tyc_confirmorder">
      <div className="tyc_address">
        <ul className="tyc_address_ul">
          <li className="tyc_fristli" onClick={backShoppingCart}>
            我的购物车
          </li>
          <li className="tyc_middleli">确认订单信息</li>
          <li className="tyc_lastli">订单提交成功</li>
        </ul>
        {/* 收货人信息 */}
        <div className="tyc_address_component">
          <h3>
            <i>收货人信息</i>
            <button className="tyc_new_address_btn1" onClick={addAddress}>
              使用新地址
            </button>
          </h3>
          <ul className="tyc_address_message">
            {address.map((v, k) => {
              return (
                <li key={v.address_id}>
                  <input type="radio"
                    name="address"
                    id={"tyc_address" + k}
                    className="addressclass"
                    value={v.address_id}
                  />
                  <label htmlFor={"tyc_address" + k}>
                    {v.consignee} {v.area} {v.street} {v.contact_phone}{" "}
                    {v.comment}
                  </label>
                  {v.default_address === "1" ? <span>默认地址</span> : ""}
                  {v.default_address === "0" ? (
                    <strong onClick={setDefaultAddresss(v.address_id, k)}>
                      设置为默认地址
                    </strong>
                  ) : (
                    ""
                  )}

                  <div>
                    <em onClick={bjsite(v)}>修改</em>
                    <i onClick={deleteAddress(k, v.address_id)}>删除</i>
                  </div>
                </li>
              );
            })}
          </ul>
          <div className="tyc_more_address">
            <span>展开其他地址</span>
            <span>收起地址</span>
          </div>
        </div>
      </div>

      <div className="tyc_mallmessage">
        <h3>商品信息</h3>
        {store.map((v, k) => {
          return (
            <div key={k}>
              <table border="1">
                <thead>
                  <tr>
                    <th className="tyc_mallName">
                      <span>{v.store_name}</span>
                    </th>
                    <th className="tyc_specification">规格</th>
                    <th className="tyc_onePrice">单价</th>
                    <th className="tyc_num">数量</th>
                    <th className="tyc_sumOnePrice">金额</th>
                  </tr>
                </thead>
                <tbody>
                  {store[k].product.map((value, key) => {
                    return (
                      <tr key={key}>
                        <td className="tyc_mail">
                          <div>
                            <img src={value.product_img} alt="" />
                          </div>
                          <span>{value.product_name}</span>
                        </td>
                        <td>
                          {value.product_number}
                          {value.product_specification}
                        </td>
                        <td>
                          ￥<i>{value.product_price}</i>
                        </td>
                        <td className="tyc_addsub_btn">
                          <div>-</div>
                          <input
                            type="text"
                            defaultValue={value.buy_number}
                            key={value.buy_number}
                            className={`buyNum${k}`}
                          />
                          <div>+</div>
                        </td>
                        <td>
                          ￥
                          <i className={`tyc_money${k}`}>
                            {(
                              parseFloat(value.product_price) * value.buy_number
                            ).toFixed(2)}
                          </i>
                        </td>
                      </tr>
                    );
                  })}

                  <tr>
                    <td colSpan="7" className="tyc_sumPrice">
                      <span>运费</span>
                      <strong>￥5.0</strong>
                      <span>商品金额</span>
                      <strong>
                        ￥<span>{v.total_price.toFixed(2)}</span>
                      </strong>
                      <span>商家合计</span>
                      <strong>
                        ￥<span>{parseFloat(v.total_price + 5).toFixed(2)}</span>
                      </strong>
                    </td>
                  </tr>
                </tbody>
              </table>
              <OtherComponent />
            </div>
          );
        })}
      </div>
      <div className="tyc_delivery_time">
        <h3>次日达·礼拜五专享</h3>
        <div>
          <span>选择配送时间：</span>

          <RangePicker
            style={{ width: "300px" }}
            showTime={{ format: "HH:mm" }}
            format="YYYY-MM-DD HH:mm"
            onChange={onChange}
            onOk={onOk}
          />
        </div>
      </div>
      <div className="tyc_settlement">
        <p>
          <strong>实付金额：</strong>
          <em>￥{sumMoneyAll.toFixed(2)}</em>
        </p>
        <div>
          <i>订单完成后可获得积分：</i>
          <span>{sumMoneyAll}积分</span>
        </div>
        <div>
          <button onClick={submitOrder}>提交订单</button>
        </div>
      </div>
    </div>
  );
}
